package com.micro.platform.oauth.config.oauth;

import com.micro.platform.oauth.component.CaptchaComponent;
import com.micro.platform.oauth.config.oauth.grant.PasswordTokenGranter;
import com.micro.platform.oauth.config.oauth.grant.RefreshTokenTokenGranter;
import com.micro.platform.oauth.config.oauth.support.LocalAccessTokenConvert;
import com.micro.platform.oauth.config.oauth.support.LocalClientDetailsService;
import com.micro.platform.oauth.config.oauth.support.LocalSubjectHandler;
import com.micro.platform.oauth.config.oauth.support.LocalUserDetailsService;
import com.micro.platform.oauth.framework.OauthManager;
import com.micro.platform.oauth.framework.config.properties.OauthProperties;
import com.micro.platform.starter.component.PasswordEncoderComponent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LocalOauthManagerConfig {

    @Autowired
    private PasswordEncoderComponent passwordEncoderComponent;

    @Autowired
    private CaptchaComponent captchaComponent;

    @Bean
    public OauthManager oauthManager(@Autowired LocalAccessTokenConvert localAccessTokenConvert,
                                     LocalClientDetailsService localClientDetailsService,
                                     LocalUserDetailsService localUserDetailsService,
                                     OauthProperties oauthProperties){
        OauthManager oauthManager = new OauthManager(oauthProperties);
        oauthManager.registerGrant(new PasswordTokenGranter(localClientDetailsService, localUserDetailsService, passwordEncoderComponent, captchaComponent));
        oauthManager.registerGrant(new RefreshTokenTokenGranter(oauthManager));
        oauthManager.getTokenService().registerAccessTokenConvert(localAccessTokenConvert);
        oauthManager.getTokenService().setSubjectHandler(new LocalSubjectHandler(oauthManager.getTokenService().getTokenStore()));
        oauthManager.setClientDetailsService(localClientDetailsService);
        oauthManager.setUserDetailsService(localUserDetailsService);
        return oauthManager;
    }
}
